package com.gcsoftware.utils;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by qs on 2018/3/28.
 */
public class WsSoapUtils {
    public static String testWebservice(String targetNamespace,String endPoint,String httpMethod, String outParamType) throws Exception {

        String soap = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tst=\"" + targetNamespace + "\">\n" +
                "   <soapenv:Header/>\n" +
                "   <soapenv:Body>\n" +
                "      <tst:GetCitiesByCountry>\n" +
                "         <!--Optional:-->\n" +
                "         <tst:CountryName>China</tst:CountryName>\n" +
                "      </tst:GetCitiesByCountry>\n" +
                "   </soapenv:Body>\n" +
                "</soapenv:Envelope>";
        return testWebservice(targetNamespace,endPoint,httpMethod,outParamType,soap);

    }

    public static String testWebservice(String targetNamespace,String endPoint,String httpMethod, String outParamType,String soap) throws Exception {
        System.out.println(soap);
        //服务的地址
//        URL wsUrl = new URL("http://www.webservicex.net/globalweather.asmx");
        URL wsUrl = new URL(endPoint);

        HttpURLConnection conn = (HttpURLConnection) wsUrl.openConnection();

        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod(httpMethod);
        conn.setRequestProperty("RequestFrm", "DsSolution");
        conn.setRequestProperty("Content-Type" , "text/xml".equals(outParamType) ? "text/xml;charset=UTF-8" : "");


        OutputStream os = conn.getOutputStream();

        os.write(soap.getBytes());

        InputStream is = conn.getInputStream();

        byte[] b = new byte[1024];
        int len = 0;
        StringBuffer s = new StringBuffer();
        while((len = is.read(b)) != -1){
            String ss = new String(b,0,len,"UTF-8");
            s.append(ss);
        }
        System.out.println(s);

        is.close();
        os.close();
        conn.disconnect();
        return s.toString();
    }
}
